package com.xxwy.groupchat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @author wy
 * @date 2020/3/6 10:52
 */
public class ChatClient {

  public void start(String host,int port){
    NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(eventExecutors)
        .channel(NioSocketChannel.class)
        .handler(new ChannelInitializer<SocketChannel>() {
          @Override
          protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new StringEncoder());
            ch.pipeline().addLast(new StringDecoder());
            ch.pipeline().addLast(new ClientHandler());
          }
        });
    try {
      ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
      Channel channel = channelFuture.channel();
      System.out.println("-------" + channel.localAddress() + "--------");
      Scanner scanner = new Scanner(System.in);
      while (scanner.hasNext()){
        String next = scanner.nextLine();
        channel.writeAndFlush(next+"\r\n");
      }
      //channelFuture.channel().closeFuture().sync();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }finally {
      eventExecutors.shutdownGracefully();
    }

  }

  public static void main(String[] args) {
    ChatClient chatClient = new ChatClient();
    chatClient.start("127.0.0.1",6666);
  }

}
